<template>
  <!--头部-->
  <div class="top" id="top">
    <!--头部bar-->
    <div class="top-bar">
      <div class="w1230 top-bar-main">
        <el-icon  style="font-size: 22px;" @click="goBack"><ArrowLeft/></el-icon>
        <ul>
          <li >
            <RouterLink v-if="loginUser==null" class="login" to="/user/login">登录</RouterLink>
            <span v-if="loginUser!=null"> {{loginUser.userName}} <a v-if="loginUser!=null" href="" @click="logout">退出</a > </span>
          </li>

          <li>
            <RouterLink v-if="loginUser==null" class="register" to="/user/register">注册</RouterLink>
          </li>
          <li v-if="loginUser!=null"><i class="fa fa-file-text-o"></i>我的订单</li>
          <li v-if="loginUser!=null">
            <RouterLink to="/shoppingCart">
              <i class="fa fa-shopping-cart"></i>购物车
            </RouterLink>
          </li>
        </ul>
      </div>
    </div>
    <!--logo+搜索-->
    <div class="top-header w1230 clear-float">
      <a href="index.html" target="_blank" class="logo">
        <img src="../assets/img/logo.png"/>
      </a>
      <div class="top-header-right">
        <!--搜索框-->
        <div class="search clear-float">
          <input type="text"  placeholder="牛奶" class="search-txt"/>
          <a href="#" class="search-btn">搜索</a>
        </div>
        <!--热搜-->
        <p class="hotkey">
          <a href="#">牛奶</a>
          <a href="#">牛仔裤</a>
          <a href="#">巧克力</a>
          <a href="#">月饼</a>
          <a href="#">抽纸</a>
          <a href="#">狗粮</a>
          <a href="#">奶粉</a>
          <a href="#">护发素</a>
          <a href="#">进口食品</a>
          <a href="#">良品铺子</a>
        </p>
      </div>
    </div>
  </div>
  <!--导航栏-->

  <div class="nav">
    <div class="w1230">
      <div id="all-goods">
        <span class="all-goods">所有商品分类</span>
        <div class="nav-er" id="nav-er">
          <ul >
            <li v-for="type in productTypeList" :key="type.id">
              <h3><RouterLink to="/classify">{{ type.productTypeName }}</RouterLink></h3>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
  <!--商品详情-->
  <div class="w1230 clear-float goods-main">
    <div class="big-img">
      <img :src="product.productImage" :alt="product.productName">
    </div>
    <div class="goods-detail">
      <h3 class="goods-title">{{ product.productName }}</h3>
      <p class="price">价格<span>￥{{ product.price }}</span></p>
      <p class="store-num">销量：<span>800件</span></p>
      <div class="update-num">
        <div>
          <input type="text" value="1" id="goodsNum"/>
          <span class="add" @click="updateQuantity('add')"></span>
          <span class="reduce" @click="updateQuantity('reduce')"></span>
        </div>
        <a href="#" id="addCart" title="添加购物车" @click="addToCar"><i class="fa fa-shopping-cart"></i>添加购物车</a><span id="tips"><i class="fa fa-check-circle-o"></i>添加成功</span>
      </div>
    </div>
    <!--店家承诺-->
    <div class="promise">
      <h3><i class="fa fa-handshake-o"></i>爱购承诺</h3>
      <p>爱购平台卖家销售并发货的商品，由平台卖家提供发票和相应的售后服务。请您放心购买！
        注：因厂家会在没有任何提前通知的情况下更改产品包装、产地或者一些附件，本司不能确保客户收到的货物与商城图片、产地、附件说明完全一致。只能确保为原厂正货！并且保证与当时市场上同样主流新品一致。若没有及时更新，请大家谅解！</p>
    </div>
  </div>
  <!--商品介绍-->
  <div class="w1230 clear-float">
    <!--商品推荐-->
    <div class="recommend goods-show">
      <h3>看了本商品的用户最终购买了</h3>
      <ul class="clear-floats">
        <li v-for="products in productAll" :key="products.id">
          <RouterLink :to="'/goodsDetail/' + products.id" @click.native="fetchProductDetails(products.id)">
            <div class="c-img">
              <img
                  :src="products.productImage"
                  :alt="products.productName"
              >
            </div>
          <!-- 显示产品名称 -->
          <p class="c-title" >{{ products.productName }}</p>
          <span class="c-price">￥{{products.price}}.00</span>
          </RouterLink>
        </li>
      </ul>
    </div>
    <!--商品介绍-->
    <div class="goods-des">
      <h3 class="goods-tro">商品介绍</h3>
      <div class="goods-info">
        <ul>
          <li><img :src="product.productImage" :alt="product.productName"></li>
          <li><img :src="product.productImage" :alt="product.productName"></li>
          <li><img :src="product.productImage" :alt="product.productName"></li>
        </ul>
      </div>
    </div>
  </div>
  <!--脚注-->
  <div class="footer">
    <p class="w1230">
      <a href="#">关于爱购</a>
      <a href="#">合作伙伴</a>
      <a href="#">营销中心</a>
      <a href="#">廉正举报</a>
      <a href="#">联系客服</a>
      <a href="#">开发平台</a>
      <a href="#">诚征英才</a>
      <a href="#">联系我们</a>
      <a href="#">网站地图</a>
      <a href="#">知识产权</a><span>|</span>
      <span>&copy;2018-2020 igo.com 版权所有</span>
    </p>
  </div>

</template>
<script>
import {doGet, doPost} from "../http/httpRequest.js";
import {messageTip} from "../util/util.js";
export default {
  name: "GoodsDetailView",
  data(){
    return{
      loginUser: {},
      product: {},
      shopCart:{},
      productAll:{},
      productTypeList:{}
    }
  },
  created() {
    this.fetchProductDetails(this.$route.params.productId);
  },
  mounted() {
    this.loginUser = JSON.parse(localStorage.getItem("user"))
    console.log(this.loginUser);
    this.loadProductList(4);
    this.loadProductTypeList(1);
  },
  methods: {
    goBack() {
      this.$router.push("/");// 返回上一个页面
    },
    fetchProductDetails(id) {
      doGet("/user/product/" +id).then((resp) => {
        if (resp.data.code === 200) {
          this.product = resp.data.data;
        }
      }).catch(error => {
        console.error('Error fetching product details:', error);
      });
    },
    updateQuantity(action) {
      // 更新输入框的值
      const goodsNum = document.getElementById('goodsNum');
      let quantity = parseInt(goodsNum.value, 10); // 转换为整数

      if (action === 'add') {
        quantity++;
      } else if (action === 'reduce' && quantity > 1) {
        quantity--;
      }
      goodsNum.value = quantity;
    },
    addShopCart() {

      // 获取商品数量
      const goodsNum = document.getElementById('goodsNum');
      const quantity = goodsNum ? parseInt(goodsNum.value, 10) : 1;

      if (!this.product.id) {
        messageTip('商品信息未正确加载，请刷新页面后重试','error');
        return;
      }
      // 构建要发送的商品对象
      const shopCartProduct = {
        productId: this.product.id,
        productNum: quantity,
        userId: this.loginUser.userId
      };
      // 发送POST请求
      doPost('/user/shopCart/addProduct', shopCartProduct)
          .then(resp => {
            if (resp.data.code === 200) {
              this.shopCart = resp.data.data;
              messageTip('添加成功', 'success');
              goodsNum.value = 1;
            } else {
              messageTip('添加失败', 'error');
            }
          })
    },
    addToCar() {
      if (this.loginUser && this.loginUser.userId) {
        this.addShopCart(this.loginUser.userId);
      } else {
        // 若用户未登录，可以给出提示让用户登录
        messageTip('请先登录再添加购物车','error');
      }
    },
    loadProductList(current) {
      doGet("/user/product", {current:current}).then((resp) =>{
        console.log(resp);
        if (resp.data.code === 200) {
          this.productAll = resp.data.data.list;
          console.log(this.productAll)
        }
      })
    },
    //分类导航栏
    loadProductTypeList(current) {
      doGet("/user/ProductType", {
        current: current
      }).then((resp) => {
       console.log(resp); // 打印完整的响应对象
       if (resp.data.code === 200) {
          this.productTypeList = resp.data.data.list;
       }
    });
  },
  }
}

</script>


<style scoped>
@import '../assets/css/reset.css';
@import "../assets/css/top.css";
@import "../assets/css/index.css";
@import "../assets/css/footer.css";
@import "../assets/css/font-awesome-4.7.0/Font-Awesome-master/css/font-awesome.min.css";
@import '../assets/css/buyerTrade.css';
@import '../assets/css/classify.css';
@import '../assets/css/deliverAddress.css';
@import '../assets/css/goodsDetail.css';
@import '../assets/css/login.css';
@import '../assets/css/shoppingCart.css';

</style>
